// init_c.rs

use boot; // 导入boot.rs
use image;// 导入image.rs

const INIT_STACK_SIZE: usize = 0x1000;
static mut BOOT_CPU_STACK: [[u8; INIT_STACK_SIZE]; PLAT_CPU_NUMBER] = [[0; INIT_STACK_SIZE]; PLAT_CPU_NUMBER];

const NOT_BSS: u64 = 0xBEEF;
static mut SECONDARY_BOOT_FLAG: [u64; PLAT_CPU_NUMBER] = [NOT_BSS; PLAT_CPU_NUMBER];

static mut CLEAR_BSS_FLAG: u64 = NOT_BSS;

#[no_mangle]
pub extern "C" fn clear_bss() {
    let bss_start_addr: u64 = &_bss_start as *const _ as u64;
    let bss_end_addr: u64 = &_bss_end as *const _ as u64;

    for i in bss_start_addr..bss_end_addr {
        unsafe {
            *(i as *mut u8) = 0;
        }
    }

    unsafe {
        CLEAR_BSS_FLAG = 0;
    }
}

#[no_mangle]
pub extern "C" fn init_c() {
    clear_bss();

    // Initialize UART before enabling MMU.
    early_uart_init();
    uart_send_string("boot: init_c\r\n");

    // Initialize Boot Page Table.
    uart_send_string("[BOOT] Install boot page table\r\n");
    init_boot_pt();

    // Enable MMU.
    el1_mmu_activate();
    uart_send_string("[BOOT] Enable el1 MMU\r\n");

    // Call Kernel Main.
    uart_send_string("[BOOT] Jump to kernel main\r\n");
    start_kernel(&mut SECONDARY_BOOT_FLAG);

    // Never reach here.
}
